﻿using System;
using System.Web;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
using Roles;
using VanTaiBLL;
using VanTaiData;
using VanTaiProperty;
using System.Web.UI.HtmlControls;
namespace VanTaiTMS.Page
{
    public partial class quan_ly_tai_khoan : System.Web.UI.Page
    {
        #region[Define]
        private DataTable dtUser;
        private DataTable dtUserDetail;
        private DataTable dtRoles;
        private DataTable dtEmployer;
        private static bool flag = false;
        public string SuggestionList = "";
        protected string StrAlert = "";
        private clsBusiness_TM_Usercs clsUser = new clsBusiness_TM_Usercs();
        private clsTMMemberBusiness clsEmployer = new clsTMMemberBusiness();
        private clsBusiness_tb_Roles clsRoles = new clsBusiness_tb_Roles();
        #endregion

        #region[Controller]
        protected void Page_Load(object sender, EventArgs e)
        {
            CheckPermisstion();
            if (!IsPostBack)
            {
                BindGirdUser();
                BindGridDropdownlist();
            }
        }
        protected void cmdAddNew_Click(object sender, EventArgs e)
        {
            flag = true;
            lbThongBaoLoi.Text = "";
            txtTenDangNhap.Enabled = true;
            ClearTextBox();
            OpenDialog("#quanlynguoidung");
            imgSave.ToolTip = "Thêm mới";
            upNewUpdatePanel.Update();
            imgSave.Visible = true;
        }
        protected void cmdEdit_Click(object sender, EventArgs e)
        {
            lbThongBaoLoi.Text = "";
            txtTenDangNhap.Enabled = false;
            for (int i = 0; i < ListViewAll.Items.Count; i++)
            {
                CheckBox chkView = (CheckBox)ListViewAll.Items[i].FindControl("chkList");
                Label lbTrangThai = (Label)ListViewAll.Items[i].FindControl("lbDuyet");
                if (chkView != null)
                {
                    if (chkView.Checked)
                    {
                        BindGridUserDetail(Convert.ToInt32(ListViewAll.DataKeys[i].Value.ToString()));
                        OpenDialog("#quanlynguoidung");
                        upNewUpdatePanel.Update();
                        imgSave.ToolTip = "Cập nhật";
                        flag = false;
                    }
                }
            }
        }
        protected void cmdDel_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < ListViewAll.Items.Count; i++)
            {
                CheckBox chkHide = (CheckBox)ListViewAll.Items[i].FindControl("chkList");
                LinkButton LinkButton2 = (LinkButton)ListViewAll.Items[i].FindControl("LinkButton2");
                if (chkHide != null)
                {
                    if (chkHide.Checked)
                    {
                        try
                        {
                            if (LinkButton2.Text == "Online")
                            {
                                lbThongBaoXoa.Text = "Tài khoản này đang được sử dụng.Bạn không thể xoá tài khoản này !";
                                OpenDialog("#thongbaoxoa");
                                upDatePanelThongBaoXoa.Update();
                                cmdAgree.Visible = false;
                                cmdClose.Text = "Đóng lại";
                            }
                            else
                            {
                                VanTaiBLL.clsBusiness_TM_Usercs.DeleteUser(int.Parse(ListViewAll.DataKeys[i].Value.ToString()));
                                BindGirdUser();
                            }
                        }
                        catch (Exception ex)
                        {
                            lbThongBaoXoa.Text = ex.ToString();
                            OpenDialog("#thongbaoxoa");
                            upDatePanelThongBaoXoa.Update();
                            cmdAgree.Visible = false;
                            cmdClose.Text = "Đóng lại";
                        }
                    }
                }
            }
        }
        protected void cmdSerach_Click(object sender, EventArgs e)
        {

        }
        protected void cmdRefesh_Click(object sender, EventArgs e)
        {

        }
        protected void cmdExport_Click(object sender, EventArgs e)
        {

        }
        //-----------------Button-Popup------------------
        protected void imgSave_Click(object sender, ImageClickEventArgs e)
        {
            if (txtTenDangNhap.Text == "")
            {
                lbThongBaoLoi.Text = "Vui lòng điền vào tên đăng nhập !";
                OpenDialog("#thongbao");
                updatePanelThongBao.Update();
            }
            if (txtMatKhau.Text == "")
            {
                lbThongBaoLoi.Text = "Vui lòng điền vào mật khẩu đăng nhập !";
                OpenDialog("#thongbao");
                updatePanelThongBao.Update();
            }
            if (drNhanVien.SelectedValue.ToString() == "-1")
            {
                lbThongBaoLoi.Text = "Vui lòng chọn nhân viên !";
                OpenDialog("#thongbao");
                updatePanelThongBao.Update();
            }
            if (drNhomQuyen.SelectedValue.ToString() == "-1")
            {
                lbThongBaoLoi.Text = "Vui lòng chọn nhóm quyền !";
                OpenDialog("#thongbao");
                updatePanelThongBao.Update();
            }
            if (txtTenDangNhap.Text != "" && txtMatKhau.Text != ""
            && drNhanVien.SelectedValue.ToString() != "-1" && drNhomQuyen.SelectedValue.ToString() != "-1")
            {
                Insert();
            }
        }
        protected void imgrefesh_Click(object sender, ImageClickEventArgs e)
        {

        }
        protected void cmdAgree_Click(object sender, EventArgs e)
        {

        }
        protected void cmdClose_Click(object sender, EventArgs e)
        {
            CloseDialog("#thongbaoxoa");
        }
        protected void cmdCloseThongBao_Click(object sender, EventArgs e)
        {
            CloseDialog("#thongbao");
        }
        //---------------List-View-----------------------
        protected void ListViewAll_ItemCommand(object sender, ListViewCommandEventArgs e)
        {
            try
            {
                HttpCookie cookie = Request.Cookies["UserLogin"];
                bool Edit = SecurityServices.HasPermisstion(StringContent.QuanLyTaiKhoan, int.Parse(cookie["RolesID"]), TypeaAudit.Edit);
                lbThongBaoLoi.Text = "";
                txtTenDangNhap.Enabled = false;
                if (e.CommandName == "Accept")
                {
                    if (Edit == false)
                    {
                        imgSave.Visible = false;
                        string SenderId = ((HtmlInputHidden)e.Item.FindControl("hiddenId")).Value;
                        BindGridUserDetail(int.Parse(SenderId));
                        OpenDialog("#quanlynguoidung");
                        upNewUpdatePanel.Update();
                        imgSave.ToolTip = "Cập nhật";
                        flag = false;
                    }
                    else
                    {
                        imgSave.Visible = true;
                        string SenderId = ((HtmlInputHidden)e.Item.FindControl("hiddenId")).Value;
                        BindGridUserDetail(int.Parse(SenderId));
                        OpenDialog("#quanlynguoidung");
                        upNewUpdatePanel.Update();
                        imgSave.ToolTip = "Cập nhật";
                        flag = false;
                    }
                }
            }
            catch (Exception ex)
            {
                lbThongBaoLoi.Text = ex.ToString();
                OpenDialog("#thongbao");
                updatePanelThongBao.Update();
            }
        }
        protected void ListViewAll_ItemDataBound(object sender, ListViewItemEventArgs e)
        {
            if (e.Item.ItemType == ListViewItemType.DataItem)
            {
                LinkButton linkListName = (LinkButton)e.Item.FindControl("linkListName");
                LinkButton LinkButton2 = (LinkButton)e.Item.FindControl("LinkButton2");
                string _jsDouble1 = ClientScript.GetPostBackClientHyperlink(linkListName, "");


                linkListName.Attributes["ondblclick"] = _jsDouble1;
                linkListName.Attributes["onclick"] = "return false;";

                if (LinkButton2.Text == "False")
                {
                    LinkButton2.Text = "Offline";
                }
                else
                {
                    LinkButton2.Text = "Online";
                }
            }
        }
        //----------------DataPager----------------------
        protected void DataPagerListAll_PreRender(object sender, EventArgs e)
        {
            BindGirdUser();
        }
        #endregion

        #region[Function]
        protected void BindGirdUser()
        {
            dtUser = clsUser.BindGridUser();
            if (dtUser != null && dtUser.Rows.Count > 0)
            {
                ListViewAll.DataSource = dtUser;
                ListViewAll.DataBind();
                ListViewAll.Visible = true;
                DataPagerListAll.Visible = true;
            }
            else
            {
                ListViewAll.Visible = false;
                DataPagerListAll.Visible = false;
            }
        }
        protected void BindGridUserDetail(int id)
        {
            dtUserDetail = clsUser.BindGridUserDetail_Edit(id);
            if (dtUserDetail != null && dtUserDetail.Rows.Count > 0)
            {
                lbID.Text = dtUserDetail.Rows[0]["Users_ID"].ToString();
                lbIDXoa.Text = dtUserDetail.Rows[0]["Users_ID"].ToString();
                txtTenDangNhap.Text = dtUserDetail.Rows[0]["UserName"].ToString();
                drNhanVien.SelectedValue = dtUserDetail.Rows[0]["IdMember"].ToString();
                drNhomQuyen.SelectedValue = dtUserDetail.Rows[0]["RolesID"].ToString();
            }
        }
        protected void BindGridDropdownlist()
        {
            dtEmployer = clsEmployer.BindGirdTMMember();
            dtRoles = clsRoles.BindGridRoles();
            if (dtEmployer != null && dtEmployer.Rows.Count > 0)
            {
                drNhanVien.DataSource = dtEmployer;
                drNhanVien.DataTextField = "FullNameMem";
                drNhanVien.DataValueField = "Member_ID";
                drNhanVien.DataBind();
            }
            if (dtRoles != null && dtRoles.Rows.Count > 0)
            {
                drNhomQuyen.DataSource = dtRoles;
                drNhomQuyen.DataTextField = "NameRoles";
                drNhomQuyen.DataValueField = "RolesID";
                drNhomQuyen.DataBind();
            }
        }
        protected void Insert()
        {
            if (flag)
            {
                InsertUserName();
            }
            else
            {
                UpdateUserName();
            }
        }
        protected bool CheckInsert()
        {
            bool kiemtra = false;
            dtUser = clsUser.BindGridUser();
            if (dtUser != null && dtUser.Rows.Count > 0)
            {
                foreach (DataRow dr in dtUser.Rows)
                {
                    if (txtTenDangNhap.Text == dr["UserName"].ToString())
                    {
                        kiemtra = true;
                    }
                }
            }
            return kiemtra;
        }
        protected void InsertUserName()
        {
            try
            {
                if (CheckInsert())
                {
                    lbThongBaoLoi.Text = "Tài khoản này đã tồn tại.Vui lòng chọn một tài khoản khác !";
                    OpenDialog("#thongbao");
                    updatePanelThongBao.Update();
                }
                else
                {
                    VanTaiProperty.clsTMUserProperty obj = new clsTMUserProperty();
                    obj.UserName = txtTenDangNhap.Text;
                    obj.Passwords = txtMatKhau.Text;
                    obj.IdMember = int.Parse(drNhanVien.SelectedValue.ToString());
                    obj.RolesID = int.Parse(drNhomQuyen.SelectedValue.ToString());
                    obj.Note = txtGhiChu.Text;
                    obj.bitSys = false;
                    VanTaiBLL.clsBusiness_TM_Usercs.InsertUser(obj);
                    ClearTextBox();
                    BindGirdUser();
                    lbThongBaoLoi.Text = "Thêm mới mẫu tin thành công !";
                    OpenDialog("#thongbao");
                    updatePanelThongBao.Update();
                }
            }
            catch (Exception ex)
            {
                lbThongBaoLoi.Text = ex.ToString();
                OpenDialog("#thongbao");
                updatePanelThongBao.Update();
            }
        }
        protected void UpdateUserName()
        {
            try
            {
                VanTaiProperty.clsTMUserProperty obj = new clsTMUserProperty();
                obj.Users_ID = int.Parse(lbID.Text);
                obj.UserName = txtTenDangNhap.Text;
                obj.Passwords = txtMatKhau.Text;
                obj.IdMember = int.Parse(drNhanVien.SelectedValue.ToString());
                obj.RolesID = int.Parse(drNhomQuyen.SelectedValue.ToString());
                obj.Note = txtGhiChu.Text;
                VanTaiBLL.clsBusiness_TM_Usercs.UpdateUser(obj);
                ClearTextBox();
                BindGirdUser();
                lbThongBaoLoi.Text = "Cập nhật mẫu tin thành công !";
                OpenDialog("#thongbao");
                updatePanelThongBao.Update();
            }
            catch (Exception ex)
            {
                lbThongBaoLoi.Text = ex.ToString();
                OpenDialog("#thongbao");
                updatePanelThongBao.Update();
            }
        }
        #endregion

        #region[OpenDialog]
        private void OpenDialog(string dialogId)
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.Append("$('" + dialogId + "').dialog('open');");
            ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(),
               "scriptKey", sb.ToString(), true);
        }
        private void CloseDialog(string dialogId)
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.Append("$('" + dialogId + "').dialog('close');");
            ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(),
               "scriptKey", sb.ToString(), true);
        }
        #endregion

        #region[ClearTextBox]
        protected void ClearTextBox()
        {
            txtTenDangNhap.Text = string.Empty;
            txtMatKhau.Text = string.Empty;
            txtGhiChu.Text = string.Empty;
            drNhanVien.SelectedIndex = -1;
            drNhomQuyen.SelectedIndex = -1;
        }
        #endregion

        #region[Permisstion]
        protected void CheckPermisstion()
        {
            HttpCookie cookie = Request.Cookies["UserLogin"];
            if (cookie != null)
            {
                bool Is_Page_All = SecurityServices.HasPermisstionPage(StringContent.QuanLyTaiKhoan, int.Parse(cookie["RolesID"]), true);
                if (Is_Page_All == true)
                {
                    bool AddNew = SecurityServices.HasPermisstion(StringContent.QuanLyTaiKhoan, int.Parse(cookie["RolesID"]), TypeaAudit.AddNew);
                    if (AddNew == false)
                    {
                        cmdAddNew.Visible = false;
                    }
                    else
                    {
                        cmdAddNew.Visible = true;
                    }
                    bool Edit = SecurityServices.HasPermisstion(StringContent.QuanLyTaiKhoan, int.Parse(cookie["RolesID"]), TypeaAudit.Edit);
                    if (Edit == false)
                    {
                        cmdEdit.Visible = false;
                    }
                    else
                    {
                        cmdEdit.Visible = true;
                    }
                    bool Del = SecurityServices.HasPermisstion(StringContent.QuanLyTaiKhoan, int.Parse(cookie["RolesID"]), TypeaAudit.Delete);
                    if (Del == false)
                    {
                        cmdDel.Visible = false;
                    }
                    else
                    {
                        cmdDel.Visible = true;
                    }
                }
                else
                {
                    Response.Redirect("error-page.aspx");
                }
            }
        }
        #endregion
    }
}